#include "ch02.h"

int main()
{
    FILE *tempfp;
    char tmpname[L_tmpnam], *cp;
    char line[256];
    char *pfx = "XXXXX";
    if((cp = tmpnam(tmpname)) == NULL)
    {
        printf("a unique name cannot be tmpnam(): %s\n", cp);
    }
    else
    {
        printf("file name get by tmpnam(): %s\n", cp);
    }
    cp = tempnam("./", pfx);
    printf("by tempnam(\"./\", pfx): %s\n", cp);
    free(cp);
    cp = tempnam("/not_exist_dir/", pfx);
    printf("by tempnam(\"/not_exist_dir/\", pfx): %s\n", cp);
    free(cp);
    // 用tmpfile()创建一个临时文件
    if((tempfp = tmpfile()) == NULL)
    {
        err_exit("tmpfile error");
    }
    else
    {
        printf("tmpfile() created a temporary file\n");
        // 向临时文件写入一行数据，然后将它读出并写至标准输出进行验证
        fputs("One line of output\n", tempfp);
        rewind(tempfp);
        if(fgets(line, sizeof(line), tempfp) == NULL)
        {
            err_exit("fgets error");
        }
        else
        {
            fputs(line, stdout);
        }
    }
    return 0;
}